package com.wlanauth.web.core.tree;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class TreeUtil {

	/**
	 * 简单方式返回一个树型结构(一般用于数据量较小的情况下)
	 * @param root
	 * @param nodes
	 * @return
	 */
	public static TreeNode simpleToTree(TreeNode root,List<TreeNode> nodes){
		List<TreeNode> children = null;
		Iterator<TreeNode> node = nodes.iterator();
		while(node.hasNext()){
			TreeNode n = node.next();
			if(n.getParentId()!=null&&
					n.getParentId().equals(root.getId())&&!n.getId().equals(root.getId())){
				if(children==null)
					children = new ArrayList<TreeNode>();
				
				children.add(TreeUtil.simpleToTree(n, nodes));
				
			}
		}
		root.setChildren(children);
		root.setLeaf(children==null);
		return root;
	}
	public static TreeNode simpleToTree(Object entity,List< ? extends Object> list,INode iNode){
		TreeNode root = iNode.entityToNode(entity);
		List<TreeNode> nodes = new ArrayList<TreeNode>();
		for(Object t:list){
			TreeNode n = iNode.entityToNode(t);
			nodes.add(n);
		}
		return TreeUtil.simpleToTree(root, nodes);
		
	}
}
